from typing import Dict, Optional, Any
from urllib.parse import urlencode


class ApiRequest:
    def __init__(
            self,
            method: str,
            api_path: str,
            body: Optional[Dict] = None,
            query_params: Optional[Dict[str, Any]] = None,
            headers: Dict[str, str] = None
    ):
        """
        method: GET, POST, PUT, PATCH, DELETE
        api_path: /v1/xxx
        """
        self.method = method.upper()
        self.api_path = api_path
        self.query_params = query_params
        self.body = body

        # 配置请求头
        if headers is not None:
            self.__headers: Dict[str, str] = headers
        else:
            self.__headers: Dict[str, str] = {}

    def headers(self) -> Dict[str, str]:
        return self.__headers

    def build_absolute_uri(self, base_url: str, with_query: bool = False) -> str:
        if with_query:
            raw_uri = self.path_url
        else:
            raw_uri = self.api_path

        if not raw_uri.startswith("http"):
            base_url = base_url.lstrip("/")
            raw_uri = f"{base_url}{raw_uri}"

        return raw_uri

    @property
    def path_url(self) -> str:
        path_url = self.api_path
        if self.query_params:
            query = urlencode(query=self.query_params)
            path_url = f'{path_url}?{query}'

        return path_url
